package com.server.api.common.util;

import cn.hutool.core.util.StrUtil;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @Description: 文件上传帮助类
 * @Author: wuming
 */
@Component
public class UploadUtil {

    @Value("${imgRealUrl}")
    private String imgRealUrl;

    private static final String CONTEXT_PATH = "/server";

    public String Upload(MultipartFile filename, String realPath) throws IOException {
        String dataDirPath = "";
        // 1.处理图片保存文件夹 imgPath代表磁盘路径
        if (imgRealUrl.lastIndexOf("/") != -1) {
            dataDirPath = imgRealUrl + CONTEXT_PATH + "/" + realPath;
        } else {
            dataDirPath = imgRealUrl + CONTEXT_PATH + realPath;
        }
        File dataDir = new File(dataDirPath);
        if (!dataDir.exists()) {
            dataDir.mkdirs();
        }
        // 2.保存图片
        // 获取文件的原始名称
        String oldFilename = filename.getOriginalFilename();
        // 获取文件的后缀名称
        String extname = "." + FilenameUtils.getExtension(oldFilename);
        String newFilename = StrUtil.uuid() + extname;
        // 处理文件信息
        filename.transferTo(new File(dataDir, newFilename));
        return CONTEXT_PATH + realPath +"/" +newFilename;
    }


    /**
     * multipartFile 转成 file 使用
     *
     * @param multipartFile
     * @return
     */
    public File transferToFile(MultipartFile multipartFile) {
        //选择用缓冲区来实现这个转换即使用java 创建的临时文件 使用 MultipartFile.transferto()方法 。
        File file = null;
        try {
            String originalFilename = multipartFile.getOriginalFilename();
            //断言
            assert originalFilename != null;
            String[] filename = originalFilename.split("\\.");
            file = File.createTempFile(filename[0], "." + filename[1]);
            multipartFile.transferTo(file);
            file.deleteOnExit();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

}
